using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using ERP.Infeartructure;

namespace ERP.Api.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    public class ItemsController : ControllerBase
    {
        private readonly ErpDbContext _db;
        public ItemsController(ErpDbContext db)
        {
            _db = db;
        }

        [HttpGet]
        public async Task<IActionResult> Get(
            [FromQuery] string? kw,
            [FromQuery] string? cat,
            [FromQuery] string? subcat,
            [FromQuery] string? stockState,
            [FromQuery] int page = 1,
            [FromQuery] int pageSize = 10)
        {
            if (page <= 0) page = 1;
            if (pageSize <= 0) pageSize = 10;

            var q = _db.MaterialItems!.AsNoTracking().AsQueryable();

            if (!string.IsNullOrWhiteSpace(kw))
            {
                var k = kw.Trim();
                q = q.Where(x =>
                    (x.ItemCode ?? "").Contains(k) ||
                    (x.ItemName ?? "").Contains(k) ||
                    (x.SpecModel ?? "").Contains(k)
                );
            }
            if (!string.IsNullOrWhiteSpace(cat)) q = q.Where(x => x.ItemType == cat);
            if (!string.IsNullOrWhiteSpace(subcat)) q = q.Where(x => x.Category == subcat);
            if (!string.IsNullOrWhiteSpace(stockState))
            {
                if (stockState == "有货") q = q.Where(x => (x.TotalStock ?? 0) > 0);
                else if (stockState == "缺货") q = q.Where(x => (x.TotalStock ?? 0) <= 0);
            }

            var total = await q.CountAsync();
            var items = await q
                .OrderBy(x => x.ItemCode)
                .Skip((page - 1) * pageSize)
                .Take(pageSize)
                .Select(x => new
                {
                    id = x.Id,
                    code = x.ItemCode,
                    name = x.ItemName,
                    spec = x.SpecModel,
                    unit = x.Unit,
                    cat = x.ItemType,
                    subcat = x.Category,
                    brand = x.Brand,
                    totalStock = x.TotalStock ?? 0,
                    stockDetails = new[] { new { name = "默认仓", qty = (int)((x.TotalStock ?? 0)) } },
                    purchasePrice = x.PurchasePrice ?? 0,
                    salePrice = x.SalesPrice ?? 0
                })
                .ToListAsync();

            return Ok(new { total, items });
        }
    }
}
